package com.lawyer.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.dynamic.Criteria;
import com.lawyer.dynamic.Restrictions;
import com.lawyer.entity.Config;
import com.lawyer.entity.Coupon;
import com.lawyer.entity.MoneyFlows;
import com.lawyer.entity.SystemUser;
import com.lawyer.entity.User;
import com.lawyer.entity.Withdrawal;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.CouponRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.SystemUserRepository;
import com.lawyer.repository.UserRepository;
import com.lawyer.repository.WithdrawalRepository;
import com.lawyer.uitls.BeanUtils;
import com.lawyer.uitls.DateUtils;

@RestController
@RequestMapping(value = "/system")
@Api(tags = "系统管理-用户")
@SuppressWarnings("all")
public class SystemUserController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SystemUserRepository systemUserRepository;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@Autowired
	private WithdrawalRepository withdrawalRepository;

	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private CouponRepository couponRepository;

	@ApiOperation(httpMethod = "GET", value = "查询用户列表", notes = "查询用户列表")
	@RequestMapping(value = "/users", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> users(String nickName, String phone, @PageableDefault(page = 0, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();
		try {
			Criteria<User> criteria = new Criteria<User>();

			if (StringUtils.isNotEmpty(nickName)) {
				criteria.add(Restrictions.like("nickName", "%" + nickName + "%", true));
			}

			if (StringUtils.isNotEmpty(phone)) {
				criteria.add(Restrictions.like("phone", phone, true));
			}

			Page<User> page = userRepository.findAll(criteria, pageable);
			msg.setData(page);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}
	
	@ApiOperation(httpMethod = "GET", value = "用户基础信息", notes = "返回用户余额，和免费咨询劵")
	@RequestMapping(value = "/userInfo", method = RequestMethod.GET)
	public HttpEntity<?> userInfo(String userId) {
		Message msg = new Message();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			User user = userRepository.findOne(userId);
			if (user != null) {
				map.put("userInfo", user);
				
				//查询用户优惠券
				List<Coupon> listCoupon = couponRepository.findByUserId(userId);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				Iterator<Coupon> iterator = listCoupon.iterator();
				while (iterator.hasNext()) {
					Coupon coupon = iterator.next();
					String endDate = sdf.format(coupon.getEndDate());
					if (DateUtils.checktime(endDate)) {
						// 已过期
						coupon.setIsExpire(true);
						couponRepository.save(coupon);
					}

				}
				map.put("listCoupon", listCoupon);

				msg.setData(map);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到用户");
			}
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "POST", value = "后台管理系统登陆", notes = "后台管理系统登陆")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public HttpEntity<?> login(@RequestBody SystemUser req) {
		Message msg = new Message();
		try {
			SystemUser systemUser = systemUserRepository.findByUsernameAndPassword(req.getUsername(), req.getPassword());

			if (systemUser != null) {
				msg.setData(systemUser);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("账号或密码错误");
			}

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}



	@ApiOperation(httpMethod = "GET", value = "用户金币流向", notes = "用户金币流向")
	@RequestMapping(value = "/moneyFlows", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> moneyFlows(String nickName, String phone, @PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();
		try {
			Criteria<MoneyFlows> criteria = new Criteria<MoneyFlows>();

			if (StringUtils.isNotEmpty(nickName)) {
				criteria.add(Restrictions.like("userName", "%" + nickName + "%", true));
			}

			if (StringUtils.isNotEmpty(phone)) {
				criteria.add(Restrictions.like("phone", phone, true));
			}

			Page<MoneyFlows> page = moneyFlowsRepository.findAll(criteria, pageable);
			msg.setData(page);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "代理或律师提现列表", notes = "stauts：0=未提现，1=提现中,2=已完成,3=已拒绝,-1= 全部")
	@RequestMapping(value = "/withdrawalList", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "第几页"),
			@ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "分页条数") })
	public HttpEntity<?> withdrawalList(String nickName, String account, @RequestParam(defaultValue = "-1") int stauts,
			@PageableDefault(page = 0, sort = { "createdDate" }, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();
		try {
			Criteria<Withdrawal> criteria = new Criteria<Withdrawal>();

			if (StringUtils.isNotEmpty(nickName)) {
				criteria.add(Restrictions.like("nickName", "%" + nickName + "%", true));
			}

			if (StringUtils.isNotEmpty(account)) {
				criteria.add(Restrictions.like("account", account, true));
			}

			if (stauts != -1) {
				criteria.add(Restrictions.eq("stauts", stauts, true));
			}

			Page<Withdrawal> page = withdrawalRepository.findAll(criteria, pageable);
			msg.setData(page);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "POST", value = "用户基本信息修改", notes = "用户基本信息修改")
	@RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
	public HttpEntity<?> updateUserInfo(@RequestBody User userReq) {
		Message msg = new Message();

		User findUser = userRepository.findOne(userReq.getId());
		if (findUser != null) {
			BeanUtils.copyPropertiesIgnoreNullValue(userReq, findUser,"dedication","userType","isCallPay");
			userRepository.save(findUser);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "赠送用户优惠券", notes = "赠送用户优惠券")
	@RequestMapping(value = "/givingCoupon", method = RequestMethod.GET)
	public HttpEntity<?> shareCoupon(String userId) {
		Message msg = new Message();
		boolean flag = false;
		try {
			User user = userRepository.findOne(userId);

			if (user != null) {
				Config configDay = configRepository.findByName("CouponValidity");// 有效期时长
				user.setDedication(true);
				Coupon coupon = new Coupon();
				coupon.setUserId(userId);
				coupon.setDescription("电话免费咨询一次");
				coupon.setTime(1);
				coupon.setIsUsed(false);
				coupon.setIsExpire(false);
				// 优惠卷过期时间
				coupon.setStartDate(new Date());

				Calendar c = Calendar.getInstance();
				c.add(Calendar.DAY_OF_MONTH, Integer.valueOf(configDay.getValue()));
				Date endDate = c.getTime();
				coupon.setEndDate(endDate);
				couponRepository.save(coupon);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("用户不存在");
			}

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "删除用户优惠券(couponId优惠券的Id)", notes = "删除用户优惠券")
	@RequestMapping(value = "/deleteCoupon", method = RequestMethod.GET)
	public HttpEntity<?> deleteCoupon(Integer couponId) {
		Message msg = new Message();
		boolean flag = false;
		try {
			Coupon coupon = couponRepository.findOne(couponId);

			if (coupon != null) {
				couponRepository.delete(coupon);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("优惠券不存在");
			}

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

}
